<?php

function __sort_root__($a, $b) {
	if ($a->idx == $b->idx)
		return 0;
	else return ($a->idx > $b->idx ? 1 : -1); 
}

class StepsAction extends CAction {

	public function run () {
		set_time_limit(1200);
		$category = "StepsAction [#".$_GET['id']."]";
		Yii::log("Loading project #".$_GET['id'],CLogger::LEVEL_INFO, $category);
		$this->controller->project = Project::model()->findByPk($_GET['id']);
		
		$this->controller->layout = 'empty';
		$this->controller->pageTitle = $this->controller->project;
		
		// TODO: unknown project !!
		// 1. on récupère tous les topics déjà créé
		Yii::log("Loading topics of project #".$_GET['id'],CLogger::LEVEL_INFO, $category);
		$tmp = $this->controller->project->topics;
		$topics = array();

		if ($tmp != null && count($tmp) > 0){
			Yii::log("Converting #".$_GET['id'],CLogger::LEVEL_INFO, $category);
			while (count($tmp) > 0) {
				$topic = array_shift($tmp);
				Yii::log("> Converting item ".$topic->key,CLogger::LEVEL_INFO, $category);
				$topic->isNewRecord = false;
				$topics[$topic->key] = $topic;
				$topic->checked = true;
				
				if ($topic->adviser_validation == ProjectTopic::INHERITS) {
					if ($topic->parent_key == null || $topics[$topic->parent_key]->adviser_validation == ProjectTopic::NO) {
						$topic->adviser_validation = ProjectTopic::NO;
					}
				}
				if ($topic->owner_validation == ProjectTopic::INHERITS) {
					if ($topic->parent_key == null || $topics[$topic->parent_key]->owner_validation == ProjectTopic::NO) {
						$topic->owner_validation = ProjectTopic::NO;
					}
				}
				if ($topic->objective == ProjectTopic::INHERITS) {
					if ($topic->parent_key == null || $topics[$topic->parent_key]->objective == ProjectTopic::NO) {
						$topic->objective = ProjectTopic::NO;
					}
				}
				
				Yii::log("Found {$topic->key} in database",CLogger::LEVEL_TRACE, "Items");
				if ($topic->children != null) {
					$tmp = array_merge($topic->children, $tmp);
				}
			}
		}
		
		$checked = (count($topics) == 0 && !isset($_POST['ProjectTopic']));
		Yii::log("Topics not in project list will be ".($checked ? "checked." : "unchecked."),CLogger::LEVEL_INFO, $category);
		
		// 2. on prend tous les items et on ajoute ceux qui n'existe pas.
		$tmp = $this->controller->project->route->steps;
		$nbweeksbefore = array('' => 0);
		$step_key = '';
		$idx = 1;
		Yii::log("Add inexistant topics.",CLogger::LEVEL_INFO, $category);
		while (count($tmp) > 0) {
			$item = array_shift($tmp);
			
			if (!array_key_exists($item->key, $topics)) {
				Yii::log("> Adding item ".$topic->key,CLogger::LEVEL_INFO, $category);
				Yii::log("Not found {$item->key} in database",CLogger::LEVEL_INFO, "Items");
				if ($item instanceof Step) {
					$step_key = $item->key;
					$nbweeksbefore[$item->key] = $nbweeksbefore[''];
					$nbweeksbefore[''] += $item->weeks_before+$item->weeks_number;
					if (count($tmp) > 0) {
						$nbweeksbefore[$tmp[0]->key] += $nbweeksbefore[''];
					}
				}
				$topic = new ProjectTopic();
				$topic->label = $item->label;
				//$topic->label = "(" . $item->weeks_before . ", " . $item->weeks_number . ")";
				$topic->description = $item->description;
				$topic->key = $item->key;
				$topic->parent_key = $item->parent_key;
				$topic->start_date = DateUtils::add(DateUtils::today(), DateUtils::DAY, ($nbweeksbefore[$step_key]+$item->weeks_before)*7);
				$topic->end_date = DateUtils::add(DateUtils::today(), DateUtils::DAY, ($nbweeksbefore[$step_key]+$item->weeks_before+$item->weeks_number)*7);
				$topic->project_id = $this->controller->project->id;
				$topic->checked = $checked;
				if ($item instanceof Topic) {
					$topic->topic_id = $item->id;
					$topic->item_type = ProjectTopic::TOPIC;
					$topic->idx = $item->orderIndex;
				} else {
					$topic->step_id = $item->id;
					$topic->item_type = ProjectTopic::STEP;
					$topic->idx = $idx++;
				}
				$topic->adviser_validation = $topic->owner_validation = $topic->objective = ProjectTopic::NO;
				$topics[$topic->key] = $topic;
				$topic->end_date = DateUtils::add(DateUtils::today(), DateUtils::DAY, ($nbweeksbefore[$step_key]+$item->weeks_before+$item->weeks_number)*7);
			}

			if ($item->topics != null) {
				$tmp = array_merge($item->topics, $tmp);
			}
		}
		
		Yii::log("Update topics tree and find root nodes.",CLogger::LEVEL_INFO, $category);
		$roots = array();
		foreach ($topics as $topic){
			if ($topic->parent_key != null && array_key_exists($topic->parent_key, $topics)) {
				if (!isset($topic->id)) {
					$idx = $topic->idx;
					$topic->parent = $topics[$topic->parent_key];
					$topic->idx = $idx;
				}
			} else {
				$roots[] = $topic;
			}
		}
		
		Yii::log(CVarDumper::dumpAsString($roots, 3, false), CLogger::LEVEL_TRACE, $category);
		$update = false;
		if (isset($_POST['ProjectTopic'])) {
			$update = true;
			Yii::log("Merging post data.",CLogger::LEVEL_INFO, $category);
			foreach ($_POST['ProjectTopic'] as $key => $topic) {
				$topic['id'] = $topics[$key]->id; 
				if ($topic['id'] == "" || ! isset($topic['id']) || $topic['id'] == null)
					unset($topic['id']);
				
				$topic['start_date'] = DateUtils::parse(Constants::YII_DISPLAY_DATE_FORMAT, $topic['start_date']);
				$topic['end_date'] = DateUtils::parse(Constants::YII_DISPLAY_DATE_FORMAT, $topic['end_date']);
				
				$arr = $topic;
				unset($arr['checked']);
				$topics[$key]->attributes = $arr;
				$topics[$key]->setChecked($topic['checked']);
				unset($arr);
			}
			
			// on sélectionne les noeuds qui ont au moins un enfant sélectionné
			/*foreach ($_POST['ProjectTopic'] as $key => $topic) {
				$r = ProjectTopicHelper::hasChildSelected($topic);
				if (isset($r)) {
					$topic->setChecked($r);
				}
			}*/
			
			Yii::log("Find last meeting.",CLogger::LEVEL_INFO, $category);
			$meeting = $this->controller->project->lastMeeting;
			
			if (!isset($meeting) || $meeting->completed){
				Yii::log("No uncompleted meeting found add a new one.",CLogger::LEVEL_INFO, $category);
				// on n'a pas de rdv, ou le dernier est fini, on en créé un
				$meeting = new Meetings();
				$meeting->completed = 0;
				$meeting->meeting_date = date("Y-m-d");
				$meeting->project_id = $this->controller->project->id;
				
				$update = $meeting->save();
			}
			
			// on enregistre l'arbre
			Yii::log("Saving items.",CLogger::LEVEL_INFO, $category);
			
			if (!$update) $stack = array();
			else $stack = array_merge($roots); 
			while (count($stack) > 0) {
				$topic = array_shift($stack);
				ProjectTopicHelper::adaptAllChildrenAndParentStatuses($topic);
				if ($topic->checked) {
					Yii::log("Saving item {$topic->key} with id {$topic->id} on project {$topic->project_id}.", CLogger::LEVEL_INFO, $category);
					if ($topic->objective == ProjectTopic::YES) {
						if ($topic->objective_date == null)
							$topic->objective_date = $meeting->meeting_date;
					} else if ($topic->objective == ProjectTopic::INHERITS) {
						$topic->objective_date = $topic->parent->objective_date;
						$topic->objective_needs = null;
						$topic->objective_contacts = null;
					} else {
						$topic->objective_date = null;
						$topic->objective_needs = null;
						$topic->objective_contacts = null;
					}
					
					if ($topic->adviser_validation == ProjectTopic::YES) {
						if ($topic->adviser_validation_date == null)
							$topic->adviser_validation_date = $meeting->meeting_date;
					} else if ($topic->adviser_validation == ProjectTopic::INHERITS) {
						$topic->adviser_validation_date = $topic->parent->adviser_validation_date;
					} else {
						$topic->adviser_validation_date = null;
					}
					
					if ($topic->owner_validation == ProjectTopic::YES) {
						if ($topic->owner_validation_date == null)
							$topic->owner_validation_date = $meeting->meeting_date;
					} else if ($topic->owner_validation == ProjectTopic::INHERITS) {
						$topic->owner_validation_date = $topic->parent->owner_validation_date;
					} else {
						$topic->owner_validation_date = null;
					}
					
					if ($topic->owner_validation != ProjectTopic::YES && $topic->adviser_validation != ProjectTopic::YES){
						$topic->validation_comment = null;
					}
					
					$update = $update & $topic->save();
					foreach ($topic->children as $child) {
						$child->setParent($topic);
						$stack[] = $child;
					}
				} else if (isset($topic->id)) {
					$topic->delete();
				} 
			}
		}
		
		usort($roots, "__sort_root__");
		
		if ($update) {
			Yii::log("Redirect.",CLogger::LEVEL_INFO, $category);
			$this->controller->redirect(array('meeting/endOfMeeting','id' => $meeting->id, 'project_id' => $this->controller->project->id));
		} else {
			Yii::log("Render.",CLogger::LEVEL_INFO, $category);
			$this->controller->render('steps', array (
				'project' => $this->controller->project,
				'topics' => $topics,
				'roots' => $roots,
				'meeting' => $meeting
			));
		}
	}

}